﻿package rd.hardcore 
{
	import flash.desktop.DockIcon;
	import flash.desktop.NativeApplication;
	import flash.desktop.SystemTrayIcon;
	import flash.display.Loader;
	import flash.display.NativeMenu;
	import flash.display.NativeMenuItem;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.net.URLRequest;
	/**
	 * ...
	 * @author Thibault Perret
	 */
	public class HardIcon
	{
		private var startUpItem:NativeMenuItem;
		private var closeItem:NativeMenuItem;
		private var trayIcon:SystemTrayIcon;
		private var dockIcon:DockIcon;
		
		public function HardIcon() 
		{
			var nm:NativeMenu = new NativeMenu();
			closeItem = new NativeMenuItem("Fermer");
			startUpItem= new NativeMenuItem("Lancer au démarrage");
			
			startUpItem.addEventListener(Event.SELECT, itemSelect);
			closeItem.addEventListener(Event.SELECT, itemSelect);
			
			nm.addItem(startUpItem);
			nm.addItem(closeItem);
			
			nm.addEventListener(Event.DISPLAYING, nmDisplaying);
			
			var icon:Loader = new Loader();
			icon.contentLoaderInfo.addEventListener(Event.COMPLETE, iconComplete);
			icon.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioErrorGesture);
			//I am a PC
			if (NativeApplication.supportsSystemTrayIcon) {
				trayIcon = NativeApplication.nativeApplication.icon as SystemTrayIcon;
				trayIcon.tooltip = "Hardcore app";
				trayIcon.menu = nm;
				icon.load(new URLRequest("icons/hc_16x16.png"));
			}
			//I am a MAC
			if (NativeApplication.supportsDockIcon) {
				dockIcon = NativeApplication.nativeApplication.icon as DockIcon;
				//tooltip n'existe pas pour dockIcon
				dockIcon.menu = nm;
				icon.load(new URLRequest("icons/hc_128x128.png"));
			}
		}
		
		private function ioErrorGesture(e:IOErrorEvent):void 
		{
			//Error
			trace("IconnError	:	"+e.text);
		}
		
		private function iconComplete(e:Event):void 
		{
			NativeApplication.nativeApplication.icon.bitmaps = [e.target.content.bitmapData];
		}
		
		private function itemSelect(e:Event):void 
		{
			switch(e.currentTarget) {
				case closeItem:
					NativeApplication.nativeApplication.exit();
				break;
				case startUpItem:
					try
					{
						if (NativeApplication.nativeApplication.startAtLogin == true) {
							NativeApplication.nativeApplication.startAtLogin = false;
							startUpItem.checked = false;
						}else {
							NativeApplication.nativeApplication.startAtLogin = false;
							startUpItem.checked = true;
						}
					}catch (err:Error) {
						//Pas géré
					}
				break;
			}
		}
		
		private function nmDisplaying(e:Event):void 
		{
			try 
			{					
				startUpItem.checked = NativeApplication.nativeApplication.startAtLogin;
			}
			catch (err:Error)
			{
				// pas installé ou raccourci
			}
			
		}
		
	}

}